package com.yanq.liancar.activity;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.adapter.CarDoctorAdapter;
import com.yanq.liancar.adapter.MailAddressAdapter;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.bean.CarCheckDataBean;
import com.yanq.liancar.bean.OdbCheckCarStatusBean;
import com.yanq.liancar.bean.OdbCheckOilWearBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.Utils;
import com.yanq.liancar.view.CustomWaveView;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CarDoctorActivity extends AppCompatActivity {

    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.custom_circle_wave_view)
    CustomWaveView waveView;
    @BindView(R.id.tv_start)
    TextView tvStart;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.tv_jiance)
    TextView tv_jiance;
    @BindView(R.id.tv_getTime)
    TextView tv_getTime;
    @BindView(R.id.ll_num)
    LinearLayout llNum;
    @BindView(R.id.tv_detection_result)
    TextView tvDetectionResult;
    @BindView(R.id.tv_lianxi)
    TextView tvLianxi;
    @BindView(R.id.tv)
    TextView tv;
    @BindView(R.id.doctor_dongli)
    RelativeLayout doctorDongli;
    @BindView(R.id.recyclerview_jiance)
    RecyclerView recyclerview_jiance;
    @BindView(R.id.img_nomessage)
    ImageView img_nomessage;
    private boolean ischeck = false;

    private CarDoctorAdapter mCarDoctorAdapter;
    private List<CarCheckDataBean.DataBean.CheckDataBean> mList=new ArrayList<>();
    private int currentProgress = 0;
    private int maxProgress = 100;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    waveView.start();
                    waveView.setCurrentProgress(currentProgress);
                    currentProgress++;
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car_doctor);
        ButterKnife.bind(this);
        Utils.setStatusBar(this, false, true);

        tvStart.setVisibility(View.VISIBLE);
        llNum.setVisibility(View.GONE);
        tvDetectionResult.setText("欢迎使用车载医生，马上开始体检吧");

        initRecyclerview();

        getRecord();


    }

    private void initRecyclerview() {
        //recyclerview_jiance.setNestedScrollingEnabled(false);
        recyclerview_jiance.setLayoutManager(new LinearLayoutManager(this));
        mCarDoctorAdapter = new CarDoctorAdapter(R.layout.item_carcheckdata, mList);
        recyclerview_jiance.setAdapter(mCarDoctorAdapter);
    }

    @OnClick({R.id.back_btn, R.id.tv_start, R.id.tv_lianxi,R.id.tv_jiance})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.tv_start:

                break;
            case R.id.tv_jiance:
                initOnlineStatus();
                break;
            case R.id.tv_lianxi:
                Bundle bundle = new Bundle();
                bundle.putInt("type", 4);
                RxActivityTool.skipActivity(CarDoctorActivity.this, SmallCDelicateCarWashActivity.class, bundle);
                break;
        }
    }


    //检测OBD是否在线
    private void initOnlineStatus() {
        OkGo.<String>post(Config.s + "llc/odbcheck/odbCheckCarStatus")
                .tag(this)
                .params("token", UserBean.getcToken(this))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.e("qeqweqe", response.body());
                        Gson gson = new Gson();
                        OdbCheckCarStatusBean info = gson.fromJson(response.body(), OdbCheckCarStatusBean.class);
                        if (info.isIsSuccess()) {
                            if ("1".equals(info.getData().getDeviceStatus())) {
                                //obd在线
                                //tvStart.setVisibility(View.GONE);
//                                waveView.setVisibility(View.GONE);
//                                new Thread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        while (currentProgress < maxProgress) {
//                                            try {
//                                                Thread.sleep(3600);
//                                                mHandler.sendEmptyMessage(0);
//                                            } catch (InterruptedException e) {
//                                                e.printStackTrace();
//                                            }
//                                        }
//                                    }
//                                }).start();
//                                //发送体检指令
                                sendInstruction();
                            } else {
                                //obd离线
                                serviceDialog("设备与车辆连接异常");
                            }
                        } else {
                            RxToast.info(info.getOutputMessage());
                        }
                    }
                });
    }

    private void serviceDialog(String str) {
        final Dialog bottomDialog = new Dialog(this);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_obd_status, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels - 320;
        params.bottomMargin = 40;
        contentView.setLayoutParams(params);
        bottomDialog.getWindow().setGravity(Gravity.CENTER);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation2);
        bottomDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        TextView textView=bottomDialog.findViewById(R.id.tv_title);
        textView.setText(str);
        TextView tv_know=bottomDialog.findViewById(R.id.tv_know);
        tv_know.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomDialog.dismiss();
            }
        });
        bottomDialog.show();
    }

    //发送指令
    private void sendInstruction(){
        OkGo.<String>get(Config.s + "llc/odbcheck/sendCarCheckCode")
                .tag(this)
                .params("token", UserBean.getcToken(this))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean baseBean = gson.fromJson(response.body(), BaseBean.class);
                        if (baseBean.isIsSuccess()) {
                            serviceDialog("体检过程大约需要10分钟,请保持发动机运转且车辆处于静止状态");
                            tvStart.setText("体检中");
                            CountDown(10);
                        } else {
                            RxToast.error(baseBean.getOutputMessage());
                        }
                    }
                });
    }

    //获取最近的一次体检记录
    private void getRecord(){
        OkGo.<String>get(Config.s + "llc/odbcheck/getCarCheckData")
                .tag(this)
                .params("token", UserBean.getcToken(this))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        CarCheckDataBean baseBean = gson.fromJson(response.body(), CarCheckDataBean.class);
                        if (baseBean.isIsSuccess()) {
                            if (baseBean.getCode()==200){
                                mList.clear();
                                mList.addAll(baseBean.getData().getCheckData());
                                mCarDoctorAdapter.notifyDataSetChanged();
                                tvStart.setVisibility(View.GONE);
                                llNum.setVisibility(View.VISIBLE);
                                tvNum.setText(baseBean.getData().getScore()+"");
                                if (baseBean.getData().getScore()==100){
                                    tvDetectionResult.setText("车辆状态良好，可安心行驶");
                                }else if (baseBean.getData().getScore()>=80&&baseBean.getData().getScore()<100){
                                    tvDetectionResult.setText("车辆存在安全隐患，请及时处理【联系附近修理厂】");
                                }else if (baseBean.getData().getScore()>=50&&baseBean.getData().getScore()<=80){
                                    tvDetectionResult.setText("车辆不安全，立即处理【联系附近修理厂】");
                                }
                                img_nomessage.setVisibility(View.GONE);
                            }else {
                                img_nomessage.setVisibility(View.VISIBLE);
                            }
                        } else {
                            RxToast.info(baseBean.getOutputMessage());
                        }
                    }
                });
    }

    /**
     * 倒计时
     *
     * @param min 倒计时间（分钟）
     */
    public void CountDown(int min) {
        //开始时间
        long start = System.currentTimeMillis();
        //结束时间
        final long end = start + min * 60 * 1000;

        final Timer timer = new Timer();
        //延迟0毫秒（即立即执行）开始，每隔1000毫秒执行一次
        timer.schedule(new TimerTask() {
            public void run() {
                //LogUtils.e("MainActivity","此处实现倒计时，指定时长内，每隔1秒执行一次该任务");
            }
        }, 0, 1000);
        //计时结束时候，停止全部timer计时计划任务
        timer.schedule(new TimerTask() {
            public void run() {
                timer.cancel();
                //LogUtils.e("asdasdasfaklhdlahda","可以获取数据了====================================================");
                getRecord();
            }
        }, new Date(end));
    }
}
